//
//  SessionRequest.swift
//  iOS
//
//  Created by gongkai on 15/6/16.
//  Copyright (c) 2015年 gongkai. All rights reserved.
//

import UIKit
import Alamofire

/**
*  Session请求,每次请求用户相关的接口时都可以用。
*  默认取NSUserDefaults.standardUserDefaults()中uid字段做为用户的凭证附加在请求参数中
*
*/
class SessionRequest: URLRequestConvertible {
    /// 用户凭证的key
    static var SessionIdentifyName = "uid"
    /// 用户凭证的读取
    static var SessionReader:()->(String?) = {
        return NSUserDefaults.standardUserDefaults().objectForKey(SessionIdentifyName) as? String
    }
    
    var url:String
    var params:Dictionary<String,AnyObject> = [:]
    var method:String = Method.GET.rawValue


    init(url:String){
        self.url = url
    }
    
    convenience init(url:String , method:String){
        self.init(url: url)
        self.method = method
    }
    
    convenience init(url:String , params:Dictionary<String,AnyObject>){
        self.init(url: url)
        self.params = params
    }
    
    var URLRequest: NSURLRequest {
        //附加sessionid
        self.params[SessionRequest.SessionIdentifyName] = SessionRequest.SessionReader()
        
        let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: self.url)!)
        mutableURLRequest.HTTPMethod = self.method
        return ParameterEncoding.URL.encode(mutableURLRequest, parameters: self.params).0
        
    }
}
